<?php
/**
 * Created by PhpStorm.
 * User: trisatria
 * Date: 1/6/14
 * Time: 3:32 PM
 */

namespace Admin\Model;

use Admin\Model\AdminUser;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Exception;

/**
 * Class AdminTopicTable
 * @package Admin\Model
 */
class AdminTagTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    /**
     * @param null $where
     * @return Paginator
     */
    public function fetchAll($where = null)
    {
        $select = new Select('tag');
        if($where != null) $select->where($where);
        // create a new result set based on the Album entity
        $resultSetPrototype = new ResultSet();
        $resultSetPrototype->setArrayObjectPrototype(new AdminTopic());
        // create a new pagination adapter object

        $paginatorAdapter = new DbSelect(
        // our configured select object
            $select,
            // the adapter to run it against
            $this->tableGateway->getAdapter(),
            // the result set to hydrate
            $resultSetPrototype
        );
        $paginator = new Paginator($paginatorAdapter);
        return $paginator;
    }

    public function saveTag(AdminTag $tag)
    {
        $data = array(
            'id' => $tag->id,
            'tag_name' => $tag->tag_name
        );

        $id = (int)$tag->id;
        if ($id == 0) {

            $this->tableGateway->insert($data);
            return $this->tableGateway->getLastInsertValue();
        } else {
            if ($this->getTag($id)) {
                $this->tableGateway->update($data, array('id' => $id));
                return $id;
            } else {
                return null;
            }
        }
    }

    public function getTag($id)
    {
        $id = (int)$id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();

        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function deleteTopic($id)
    {
        $this->tableGateway->delete(array('id' => $id));
    }



}
